package pers.jing.android.helper

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import pers.jing.android.helper.model.CommandResult
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import kotlin.collections.component1
import kotlin.collections.component2

/**
 * 命令行工具
 */
object CmdTools {

    /**
     * 封装执行命令的脚本, 分别收集输入流和错误流
     */
    suspend fun executeCommand(commands: List<String>,
                               charset: Charset = StandardCharsets.UTF_8
    ): CommandResult = coroutineScope {
        var process = ProcessBuilder(commands)
            .start()
        val resultDeferred = async(Dispatchers.IO) {
            process.inputReader(charset).use {
                it.readLines()
            }
        }
        val errorDeferred = async(Dispatchers.IO) {
            process.errorReader(charset).use {
                it.readLines()
            }
        }
        val (result, error) = awaitAll(resultDeferred, errorDeferred)

        val code = process.waitFor()
        CommandResult(code, result, error)
    }
}